/*
 * @Description: 渠道管理业务逻辑组合式函数
 * @Author: 张效玮2 yythis@163.com
 * @Date: 2025-08-11 14:05:05
 * @LastEditors: 张效玮2
 * @LastEditTime: 2025-08-25 11:07:01
 *
 * 优化说明：
 * 1. 去除重复逻辑，提取公共函数
 * 2. 为模拟数据预留接口位置
 * 3. 简化数据流，使用展开语法
 * 4. 添加接口调用预留函数
 */

import type {
  CreateChannelRequestData
} from "@/common/apis/channel-management/type"
import { ElMessage } from "element-plus"
import { computed, ref, watch } from "vue"
import {
  createChannelListApi
} from "@/common/apis/channel-management"

// 渠道服务商接口
export interface Channel {
  id: string
  name: string
  manager: string
  contactPhone: string
  status: "active" | "inactive"
  createTime: string
  cooperationStartDate: string
  agents: Agent[]
}

// 代理商接口
export interface Agent {
  id: string
  name: string
  manager: string
  phone: string
  status: "active" | "inactive"
  level: 2 | 3
  parentId?: string
  channelId: string
  createTime: string
  expandable?: boolean
  expanded?: boolean
  children?: Agent[]
  levelText: string // 级别文本，不是可选的
}

export function useChannelManagement() {
  // 页面状态
  const listLoading = ref(false)
  const detailLoading = ref(false)
  const searchKeyword = ref("")

  // 分页状态
  const currentPage = ref(1)
  const pageSize = ref(10)
  const _total = ref(0)

  // 选中的渠道
  const selectedChannel = ref<Channel | null>(null)

  // 弹窗状态
  const showCreateChannelDialog = ref(false)
  const showEditChannelDialog = ref(false)
  const showCreateSecondAgentDialog = ref(false)
  const showCreateThirdAgentDialog = ref(false)
  const showEditSecondAgentDialog = ref(false)
  const showEditThirdAgentDialog = ref(false)

  // 当前编辑的渠道和代理商
  const currentEditChannel = ref<Channel | null>(null)
  const currentEditAgent = ref<Agent | null>(null)
  const currentParentAgent = ref<Agent | null>(null)

  // 渠道数据 - 预留接口位置
  const channels = ref<Channel[]>([])

  // 模拟数据 - 开发阶段使用，生产环境删除
  const mockChannels: Channel[] = [
    {
      id: "1",
      name: "华东区域服务商",
      manager: "李经理",
      contactPhone: "13800138001",
      status: "active",
      createTime: "2024-01-15",
      cooperationStartDate: "2024-01-15T00:00:00",
      agents: []
    },
    {
      id: "2",
      name: "华南区域服务商",
      manager: "王经理",
      contactPhone: "13800138002",
      status: "active",
      createTime: "2024-01-20",
      cooperationStartDate: "2024-01-20T00:00:00",
      agents: []
    },
    {
      id: "3",
      name: "华北区域服务商",
      manager: "张经理",
      contactPhone: "13800138003",
      status: "inactive",
      createTime: "2024-02-01",
      cooperationStartDate: "2024-02-01T00:00:00",
      agents: []
    }
  ]

  // 初始化模拟数据 - 开发阶段使用
  channels.value = mockChannels

  // 代理商数据 - 预留接口位置
  const agents = ref<Agent[]>([])

  // 模拟代理商数据 - 开发阶段使用，生产环境删除
  const mockAgents: Agent[] = [
    {
      id: "a1",
      name: "上海代理商A",
      manager: "陈经理",
      phone: "13800138011",
      status: "active",
      level: 2,
      channelId: "1",
      createTime: "2024-01-20",
      expandable: true,
      expanded: false,
      levelText: "二级代理",
      children: [
        {
          id: "a1-1",
          name: "浦东分销商",
          manager: "刘经理",
          phone: "13800138021",
          status: "active",
          level: 3,
          parentId: "a1",
          channelId: "1",
          createTime: "2024-02-01",
          levelText: "三级代理"
        }
      ]
    },
    {
      id: "a2",
      name: "杭州代理商B",
      manager: "赵经理",
      phone: "13800138012",
      status: "active",
      level: 2,
      channelId: "1",
      createTime: "2024-01-25",
      expandable: true,
      expanded: false,
      levelText: "二级代理",
      children: []
    },
    {
      id: "a3",
      name: "深圳代理商C",
      manager: "孙经理",
      phone: "13800138013",
      status: "active",
      level: 2,
      channelId: "2",
      createTime: "2024-01-30",
      expandable: true,
      expanded: false,
      levelText: "二级代理",
      children: []
    }
  ]

  // 初始化模拟代理商数据 - 开发阶段使用
  agents.value = mockAgents

  // 计算属性：获取指定渠道的代理商列表
  const getChannelAgents = computed(() => (channelId: string) => {
    return agents.value.filter(agent => agent.channelId === channelId)
  })

  // 计算属性：获取渠道的代理数量
  const getChannelAgentCount = computed(() => (channelId: string) => {
    return agents.value.filter(agent => agent.channelId === channelId).length
  })

  // 获取渠道列表 - 预留接口位置
  const _fetchChannelList = async () => {
    // TODO: 调用获取渠道列表API接口
    // const response = await getChannelListApi()
    // channels.value = response.data
  }

  // 获取渠道详情 - 预留接口位置
  const _fetchChannelDetail = async (_id: string) => {
    // TODO: 调用获取渠道详情API接口
    // const response = await getChannelDetailApi(id)
    // return response.data
  }

  // 简单的展开/收起切换
  const toggleAgentExpand = (agent: Agent) => {
    agent.expanded = !agent.expanded
  }

  // 开发阶段初始化模拟数据
  const initializeMockData = () => {
    channels.value = mockChannels
    agents.value = mockAgents

    // 自动选中第一个渠道
    if (channels.value.length > 0 && !selectedChannel.value) {
      selectedChannel.value = channels.value[0]
    }
  }

  // 初始化 - 开发阶段使用模拟数据，生产环境调用接口
  initializeMockData()

  // 计算属性
  const filteredChannels = computed(() => {
    if (!searchKeyword.value) return channels.value
    return channels.value.filter(channel =>
      channel.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      || channel.manager.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  })

  // 分页计算
  const paginatedChannels = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    return filteredChannels.value.slice(startIndex, endIndex)
  })

  const _totalCount = computed(() => filteredChannels.value.length)

  // 监听筛选结果变化，自动选中第一个
  watch(filteredChannels, (newFilteredChannels) => {
    // 重置分页到第一页
    currentPage.value = 1

    if (newFilteredChannels.length > 0) {
      // 如果当前选中的渠道不在筛选结果中，自动选中第一个
      if (!selectedChannel.value || !newFilteredChannels.find(c => c.id === selectedChannel.value?.id)) {
        selectedChannel.value = newFilteredChannels[0]
      }
    } else {
      // 如果没有筛选结果，清空选中状态
      selectedChannel.value = null
    }
  }, { immediate: true })

  // 监听 agents 变化，自动同步到 channels.agents
  watch(agents, () => {
    channels.value.forEach((channel) => {
      channel.agents = agents.value.filter(agent => agent.channelId === channel.id)
    })
  }, { deep: true })

  const headerButtons = computed(() => [
    {
      text: "创建渠道",
      type: "primary" as const,
      icon: "Plus",
      onClick: () => showCreateChannelDialog.value = true
    }
  ])

  // 选择渠道
  const selectChannel = (channel: Channel) => {
    selectedChannel.value = channel
  }

  // 编辑渠道
  const editChannel = (channel: Channel) => {
    currentEditChannel.value = channel
    showEditChannelDialog.value = true
  }

  // 创建渠道
  const createChannel = async (data: CreateChannelRequestData) => {
    try {
      // 调用创建渠道API接口
      const response = await createChannelListApi(data)

      if (response.code === 200) {
        // API 调用成功，直接使用回传回来的data构建新渠道对象
        const newChannel: Channel = {
          id: response.data.id || Date.now().toString(),
          name: data.channelName,
          manager: data.contactPerson,
          contactPhone: data.contactPhone,
          status: data.status === "合作中" ? "active" : "inactive",
          createTime: new Date().toISOString().split("T")[0],
          cooperationStartDate: data.cooperationStartDate,
          agents: []
        }

        channels.value.push(newChannel)
        selectedChannel.value = newChannel

        ElMessage.success("渠道服务商创建成功")
        showCreateChannelDialog.value = false
      } else {
        ElMessage.error(response.message || "创建渠道失败")
      }
    } catch (error) {
      console.error("创建渠道失败:", error)
      ElMessage.error("创建渠道失败，请检查网络连接")
      showCreateChannelDialog.value = false
    }
  }

  // 更新渠道
  const updateChannel = (data: any) => {
    if (!currentEditChannel.value) return

    const index = channels.value.findIndex(c => c.id === currentEditChannel.value!.id)
    if (index !== -1) {
      // 直接使用字段名，保持一致性
      const mappedData = {
        name: data.name,
        manager: data.manager,
        contactPhone: data.phone,
        status: data.status
      }

      channels.value[index] = {
        ...channels.value[index],
        ...mappedData
      }

      // 更新选中的渠道
      if (selectedChannel.value?.id === currentEditChannel.value.id) {
        selectedChannel.value = channels.value[index]
      }
    }

    ElMessage.success("渠道服务商更新成功")
    showEditChannelDialog.value = false
    currentEditChannel.value = null
  }

  // 打开创建二级代理弹窗
  const openCreateSecondAgentDialog = () => {
    if (!selectedChannel.value) {
      ElMessage.warning("请先选择一个渠道服务商")
      return
    }
    showCreateSecondAgentDialog.value = true
  }

  // 创建二级代理 - 直接添加，Vue自动响应式更新
  const createSecondAgent = (data: any) => {
    if (!selectedChannel.value) return

    // TODO: 生产环境调用 createSecondAgentApi 接口
    // const response = await createSecondAgentApi(data)

    const newAgent: Agent = {
      id: `a${Date.now()}`,
      createTime: new Date().toISOString().split("T")[0],
      expandable: true,
      expanded: false,
      levelText: "二级代理",
      ...data
    }

    agents.value.push(newAgent)
    ElMessage.success("二级代理创建成功")
    showCreateSecondAgentDialog.value = false
  }

  // 创建三级代理 - 直接添加，Vue自动响应式更新
  const createThirdAgent = (data: any) => {
    if (!currentParentAgent.value) return

    // TODO: 生产环境调用 createThirdAgentApi 接口
    // const response = await createThirdAgentApi(data)

    const newAgent: Agent = {
      id: `a${Date.now()}-${Math.random().toString(36).substr(2, 5)}`,
      createTime: new Date().toISOString().split("T")[0],
      levelText: "三级代理",
      ...data
    }

    // 三级代理只添加到父代理的children数组中，这样可以避免数据重复，保持数据结构的清晰性
    if (!currentParentAgent.value.children) {
      currentParentAgent.value.children = []
    }
    currentParentAgent.value.children.push(newAgent)
    currentParentAgent.value.expandable = true

    ElMessage.success("三级代理创建成功")
    showCreateThirdAgentDialog.value = false
    currentParentAgent.value = null
  }

  // 编辑代理商
  const editAgent = (agent: Agent) => {
    currentEditAgent.value = agent
    if (agent.level === 2) {
      showEditSecondAgentDialog.value = true
    } else {
      showEditThirdAgentDialog.value = true
    }
  }

  // 更新二级代理 - 直接修改，Vue自动响应式更新
  const updateSecondAgent = (data: any) => {
    if (!currentEditAgent.value) return

    // 直接修改代理对象，Vue自动处理响应式
    Object.assign(currentEditAgent.value, data)

    ElMessage.success("二级代理更新成功")
    showEditSecondAgentDialog.value = false
    currentEditAgent.value = null
  }

  // 更新三级代理 - 直接修改，Vue自动响应式更新
  const updateThirdAgent = (data: any) => {
    if (!currentEditAgent.value) return

    // 直接修改代理对象，Vue自动处理响应式
    Object.assign(currentEditAgent.value, data)

    ElMessage.success("三级代理更新成功")
    showEditThirdAgentDialog.value = false
    currentEditAgent.value = null
  }

  // 添加子代理（三级代理）
  const addSubAgent = (agent: Agent) => {
    currentParentAgent.value = agent
    showCreateThirdAgentDialog.value = true
  }

  // 分页相关方法
  const handlePageChange = (page: number) => {
    currentPage.value = page
    // 如果当前选中的渠道不在当前页，自动选中第一个
    if (paginatedChannels.value.length > 0) {
      const currentSelected = paginatedChannels.value.find(c => c.id === selectedChannel.value?.id)
      if (!currentSelected) {
        selectedChannel.value = paginatedChannels.value[0]
      }
    }
  }

  const handleSizeChange = (size: number) => {
    pageSize.value = size
    currentPage.value = 1 // 重置到第一页
    // 自动选中第一个
    if (paginatedChannels.value.length > 0) {
      selectedChannel.value = paginatedChannels.value[0]
    }
  }

  const resetPagination = () => {
    currentPage.value = 1
    pageSize.value = 10
  }

  // 删除代理商 - 直接删除，Vue自动响应式更新
  const deleteAgent = (agent: Agent) => {
    if (agent.level === 2) {
      // 如果有子代理，先删除子代理
      if (agent.children && agent.children.length > 0) {
        agent.children.forEach((child) => {
          const childIndex = agents.value.findIndex(a => a.id === child.id)
          if (childIndex !== -1) {
            agents.value.splice(childIndex, 1)
          }
        })
      }
    }

    // 删除代理本身
    const index = agents.value.findIndex(a => a.id === agent.id)
    if (index !== -1) {
      agents.value.splice(index, 1)
      ElMessage.success(`${agent.level === 2 ? "二级" : "三级"}代理删除成功`)
    }
  }

  // 切换代理商状态
  const toggleAgentStatus = (agent: Agent) => {
    const newStatus = agent.status === "active" ? "inactive" : "active"
    agent.status = newStatus

    // 同步更新agents数组
    const index = agents.value.findIndex(a => a.id === agent.id)
    if (index !== -1) {
      agents.value[index].status = newStatus
    }

    // 同步更新渠道中的代理商数据
    const channelIndex = channels.value.findIndex(c => c.id === agent.channelId)
    if (channelIndex !== -1 && channels.value[channelIndex].agents) {
      if (agent.level === 2) {
        const channelAgentIndex = channels.value[channelIndex].agents!.findIndex(a => a.id === agent.id)
        if (channelAgentIndex !== -1) {
          channels.value[channelIndex].agents![channelAgentIndex].status = newStatus
        }
      } else if (agent.level === 3 && agent.parentId) {
        const channelAgentIndex = channels.value[channelIndex].agents!.findIndex(a => a.id === agent.parentId)
        if (channelAgentIndex !== -1 && channels.value[channelIndex].agents![channelAgentIndex].children) {
          const childIndex = channels.value[channelIndex].agents![channelAgentIndex].children!.findIndex(c => c.id === agent.id)
          if (childIndex !== -1) {
            channels.value[channelIndex].agents![channelAgentIndex].children![childIndex].status = newStatus
          }
        }
      }

      // 更新选中的渠道
      if (selectedChannel.value?.id === channels.value[channelIndex].id) {
        selectedChannel.value = channels.value[channelIndex]
      }
    }

    ElMessage.success(`代理商状态已${newStatus === "active" ? "启用" : "禁用"}`)
  }

  // 切换渠道状态
  const toggleChannelStatus = (channel: Channel) => {
    const newStatus = channel.status === "active" ? "inactive" : "active"
    channel.status = newStatus

    // 同步更新channels数组
    const index = channels.value.findIndex(c => c.id === channel.id)
    if (index !== -1) {
      channels.value[index].status = newStatus
    }

    // 更新选中的渠道
    if (selectedChannel.value?.id === channel.id) {
      selectedChannel.value.status = newStatus
    }

    ElMessage.success(`渠道状态已${newStatus === "active" ? "启用" : "禁用"}`)
  }

  // 删除渠道
  const deleteChannel = (channel: Channel) => {
    const index = channels.value.findIndex(c => c.id === channel.id)
    if (index !== -1) {
      // 删除该渠道下的所有代理商
      if (channel.agents && channel.agents.length > 0) {
        channel.agents.forEach((agent) => {
          deleteAgent(agent)
        })
      }

      // 删除渠道
      channels.value.splice(index, 1)

      // 如果删除的是当前选中的渠道，清空选择
      if (selectedChannel.value?.id === channel.id) {
        selectedChannel.value = null
      }

      ElMessage.success("渠道删除成功")
    }
  }

  return {
    // 状态
    selectedChannel,
    searchKeyword,
    headerButtons,
    filteredChannels,
    paginatedChannels,
    listLoading,
    detailLoading,

    // 分页状态
    currentPage,
    pageSize,
    total: _total,

    // 弹窗状态
    showCreateChannelDialog,
    showEditChannelDialog,
    showCreateSecondAgentDialog,
    showCreateThirdAgentDialog,
    showEditSecondAgentDialog,
    showEditThirdAgentDialog,

    // 当前编辑对象
    currentParentAgent,
    currentEditAgent,
    currentEditChannel,

    // 计算属性
    getChannelAgents,
    getChannelAgentCount,

    // 方法
    selectChannel,
    editChannel,
    createChannel,
    updateChannel,
    openCreateSecondAgentDialog,
    createSecondAgent,
    createThirdAgent,
    editAgent,
    updateSecondAgent,
    updateThirdAgent,
    toggleAgentExpand,
    addSubAgent,
    deleteAgent,
    toggleAgentStatus,
    toggleChannelStatus,
    deleteChannel,
    handlePageChange,
    handleSizeChange,
    resetPagination
  }
}
